package com.hdumooc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @description: Druid 工具类
 * @author: Jieyao Lu
 * @date: 2023/11/18 15:49
**/
public class DruidUtils {

    // 1.定义数据源
    public static DataSource dataSource;

    // 2.静态代码块
    static {
        try {
            // 3.创建属性集对象
            Properties properties = new Properties();
            // 4.加载配置文件 Druid无法主动加载配置文件，需要手动指定文件位置
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            // 5.Properties 对象的 load 方法：从字节流中读取配置信息
            properties.load(inputStream);
            // 6.通过工厂类获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接的方法
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 获取 Druid 连接池（数据源）
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 释放资源
     */
    public static void close(Connection connection, Statement statement) {
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
